package com.auto.survey.activity.monitoring.ctrlmeasure

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.util.TypedValue
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.auto.survey.R
import com.auto.survey.activity.monitoring.adapter.CtrlAddManagerAdapter
import com.auto.survey.activity.monitoring.adapter.CtrlAddManagerAdapter.CtrlAddViewHodler
import com.auto.survey.base.CustomApplication

class GridDragCallback(
    private val adapter: CtrlAddManagerAdapter
) : ItemTouchHelper.Callback() {
    // 记录当前是否正在拖动
    private var isDragging = false

    // 1. 设置可拖动的方向（四向：上下左右）
    override fun getMovementFlags(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder
    ): Int {
        val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
        return makeMovementFlags(dragFlags, 0) // 不处理滑动删除
    }

    // 2. 处理拖动时的数据交换逻辑
    override fun onMove(
        recyclerView: RecyclerView,
        source: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        val fromPos = source.adapterPosition
        val toPos = target.adapterPosition
        // 检查位置有效性
        if (fromPos == RecyclerView.NO_POSITION || toPos == RecyclerView.NO_POSITION) {
            return false
        }

        adapter.swapItems(fromPos, toPos) // 交换数据集
        adapter.notifyItemMoved(fromPos, toPos) // 通知 RecyclerView 更新视图
        return true
    }

    // 3. 滑动删除（不需要，返回空实现）
    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}

    // 4. 拖拽时的视觉反馈（提升体验）
    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        super.onSelectedChanged(viewHolder, actionState)
        isDragging = actionState == ItemTouchHelper.ACTION_STATE_DRAG
        if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
            // 设置阴影和缩放效果（网格布局更适用层叠视觉）
            val holder = viewHolder as CtrlAddViewHodler
            holder.tv_item_ctrladd.setBackgroundResource(R.drawable.item_ctrladd_choiced_bg)
            viewHolder.itemView?.apply {
                elevation = 12.dpToPx().toFloat() // Android 5.0+ 阴影
                scaleX = 1.05f // 轻微放大
                scaleY = 1.05f
                background = null // 半透明背景区分
            }
        }
    }

    // 外部调用此方法停止拖动
    fun stopDragging() {
        if (isDragging) {
            isDragging = false
            // 重置状态并刷新 UI
            adapter.resetDragState()
        }
    }

    // 5. 拖拽结束后恢复视图状态
    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
        super.clearView(recyclerView, viewHolder)
        val holder = viewHolder as CtrlAddViewHodler
        holder.tv_item_ctrladd.setBackgroundResource(R.drawable.item_ctrladd_unchoiced_bg)
        viewHolder.itemView.apply {
            elevation = 0.dpToPx().toFloat()
            scaleX = 1.0f
            scaleY = 1.0f
            background = null // 移除临时背景
        }

        adapter.resetDragState()

    }

    // 可选：控制哪些位置可拖动（避免顶部头布局或底部固定项）
    override fun isLongPressDragEnabled(): Boolean {
        return false // 禁用默认长按触发，改为手动调用
    }

    fun Int.dpToPx(): Int {
        // TypedValue.COMPLEX_UNIT_DIP 表示以 dp 为单位，转换为 px
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            this.toFloat(),
            CustomApplication.getContext().resources.displayMetrics
        ).toInt()
    }

    // 给 Float 类型添加 dp 转 px 的扩展函数（如需处理小数 dp）
    fun Float.dpToPx(): Float {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            this,
            CustomApplication.getContext().resources.displayMetrics
        )
    }
}